<template>
  <div class="fillcontain">
    <bt-col-header title="新增规则组"></bt-col-header>
    <div class="form-container">
      <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px" >
        <div class="row">
          <div class="col-md-6">
            <el-form-item label="规则组标识" label-width="120px" prop="groupIdentify">
              <el-input v-model="dataForm.groupIdentify" placeholder="规则组标识" disabled></el-input>
            </el-form-item>
          </div>
          <div class="col-md-6">
            <el-form-item label="规则组名称" label-width="120px" prop="groupName">
              <el-input v-model="dataForm.groupName" placeholder="规则组名称"></el-input>
            </el-form-item>
          </div>
        </div>

        <div class="row">
          <!-- <div class="col-md-6">
            <el-form-item label="规则组类型" label-width="120px" prop="groupType">
              <el-select
                v-model="dataForm.groupType"
                :disabled="isDisabled"
                filterable
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in groupTypes"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  @click.native="changeGroupType(item)"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </div> -->
          <div class="col-md-6">
            <el-form-item label="是否有效" label-width="120px" prop="isEffect">
              <el-switch v-model="dataForm.isEffect" active-color="#13ce66" inactive-color="#ff4949" on-value="1" on-text="是" off-text="否" off-value="0">
              </el-switch>
            </el-form-item>
          </div>
        </div>
        <el-form-item label="规则组描述" label-width="120px" prop="groupDesc">
          <el-input type="textarea" :rows="3" v-model="dataForm.groupDesc" placeholder="规则组描述"></el-input>
        </el-form-item>

        <div class="row">
          <el-form-item label="关联模型" label-width="120px">
            <el-checkbox-group v-model="checkEntity" @change="handleCheckedChange">
              <div class="col-md-4" v-for="entity in entitysProperties" :key="entity.entityId">
                <el-checkbox :label="entity.entityId + ''" :key="entity.entityId">{{ entity.label }}
                </el-checkbox>
              </div>
            </el-checkbox-group>
          </el-form-item>
        </div>
      </el-form>

      <div class="mb10 pl20" v-if="dataForm.groupType === '1'">
        <bt-col-header title="规则"></bt-col-header>
        <div class="row mb10">
          <div class="col-md-12">
            <el-button type="info" plain icon="circle-plus" @click="addRule()">新增</el-button>
          </div>
        </div>
      </div>

      <div v-if="dataForm.groupType === '1'">
        <!-- 列表 -->
        <el-table :data="dataList" border style="width: 100%">
          <el-table-column type="expand">
            <template slot-scope="scope">
              <div class="row">
                <div class="col-md-12">
                  <el-card class="box-card">
                    <div class="rule_content">
                      <div class="row">
                        <span class="txt1">如果</span>
                      </div>
                      <div class="row" v-for="(condition, cindex) in scope.row.conditionInfoList" :key="cindex">
                        <div class="row" v-if="cindex == 0">
                          <div class="col-md-10">
                            <span class="txt3">{{ condition.conditionDesc }}</span>
                          </div>
                        </div>
                        <div class="row" v-else-if="cindex != 0">
                          <div class="col-md-10">
                            <span class="txt2">并且 </span>
                            <span class="txt5">{{ condition.conditionDesc }}</span>
                          </div>
                        </div>
                      </div>
                      <div class="row">
                        <span class="txt1">那么</span>
                      </div>
                      <div class="row" v-for="(action, aindex) in scope.row.actionInfoList" :key="aindex">
                        <div class="row">
                          <div class="col-md-10">
                            <span class="txt4">{{ action.actionDesc }}</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </el-card>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="ruleCode" header-align="center" align="center" width="180" label="规则编号">
          </el-table-column>
          <el-table-column prop="ruleName" header-align="center" align="center" width="180" label="规则名称">
          </el-table-column>
          <el-table-column prop="groupName" header-align="center" align="center" label="所属规则组">
          </el-table-column>
          <el-table-column prop="ruleDesc" header-align="center" align="center" label="规则描述">
          </el-table-column>
          <el-table-column prop="isEffect" header-align="center" align="center" label="状态">
            <template slot-scope="scope">
              {{ scope.row.isEffect | isEffectFilter }}
            </template>
          </el-table-column>

          <el-table-column header-align="center" align="center" width="150" label="操作">
            <template slot-scope="scope">
              <el-button v-if="isAuth('rule:edit')" type="text" size="small" @click="editRule(scope.row.ruleId)">
                修改
              </el-button>
              <el-button v-if="scope.row.isEffect === '1'" type="text" size="small" @click="edit(scope.row)">禁用
              </el-button>
              <el-button v-if="scope.row.isEffect === '0'" type="text" size="small" @click="edit(scope.row)">启用
              </el-button>
              <el-button type="text" size="small" @click="edit(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="row">
          <div class="col-md-12 text-right">
            <div class="pagination">
              <!-- 分页 -->
              <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="page.pageIndex" :page-sizes="[10, 20, 50, 100]" :page-size="page.pageSize" :total="page.totalPage" layout="total, sizes, prev, pager, next, jumper">
              </el-pagination>
            </div>
          </div>
        </div>
      </div>
      <div v-if="dataForm.groupType === '2'">
        <!-- 列表 -->
        <!--    :conditionDivisorList="conditionDivisorList"
                          :actionDivisorList="actionDivisorList" -->
        <desion-or-update :dataForm="dataForm" :checkEntity="checkEntitys" :versionType="versionType" ref="desionOrUpdate">
        </desion-or-update>
      </div>
    </div>
    

    <div class="content-footer" v-if="dataForm.groupType === '2'">
      <el-button type="info" plain @click="dataFormSubmit()">确定</el-button>
      <el-button @click="toList">取消</el-button>
    </div>
    <div class="content-footer" v-if="dataForm.groupType === '1'">
      <el-button type="info" plain @click="dataFormSubmit2()">确定</el-button>
      <el-button @click="toList">取消</el-button>
    </div>
  </div>
</template>

<script>
import { saveData, getData, saveRuleGroup } from "@/api/ruleConfig/groupInfo";
import { entityList } from "@/api/baseConfig/entity";
import { pageData, updateData } from "@/api/ruleConfig/rule";
import constant from "@/api/constant";
import desionOrUpdate from "../decision/add-or-update";
import { listActionDivisorData } from "@/api/baseConfig/actionDivisor";
import { listConditionDivisorData } from "@/api/baseConfig/conditionDivisor";

export default {
  data() {
    return {
      isEntityEdit: false,
      versionType: "d",
      // conditionDivisorList: [],
      // actionDivisorList: [],
      checktaskdes: { demandName: "选择任务" },
      checktaskarry: [],
      entityList: [],
      checkEntitys: [],
      conditionList: [], //表头信息
      tableDatas: [], //决策表数据
      groupTypes: constant.ruleConfig.groupTypes,
      checkEntity: [],
      dataList: [],
      isDisabled: false,
      visible: false,
      dataForm: {
        id: null,
        groupName: "",
        groupDesc: "",
        groupIdentify: "",
        remark: "",
        groupType: "1",
        isEffect: "1",
      },
      entitysProperties: [],
      dataRule: {
        groupName: [
          { required: true, message: "规则组名称不能为空", trigger: "blur" },
          { max: 50, message: "长度不能大于50", trigger: "blur" },
        ],
        groupType: [
          { required: true, message: "规则组类型不能为空", trigger: "blur" },
        ],
      },
      itemDataForm: {
        itemData: [],
      },
      page: {
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
      },
    };
  },
  created() {
  },
  activated() {
    this.init(this.$route.params.id, this.versionType);
  },
  components: {
    desionOrUpdate,
  },

  mounted() {
    let id = this.$route.params.id;
    if (this.$route.params.type) {
      let type = this.$route.params.type;
      this.versionType = type;
    }
    this.init(id, this.versionType);
  },
  methods: {
    checktask(val) {
      this.checktaskdes = val;
    },
    addOreditDecisicn() {
      if (this.dataForm.id) {
        constant.clearTag(this);
        this.$router.push({
          path: "/drools-ruleConfig/decision/add-or-update/" + this.dataForm.id,
        });
      }
    },
    changeGroupType(item) {
    },
    toList() {
      constant.clearTag(this);
      this.$router.push({ name: constant.routerName.listGroup });
    },
    handleCheckedChange(data) {
      this.isEntityEdit = true;
      this.initEntity();
    },

    initEntity() {
      this.checkEntitys = [];
      this.checkEntity.forEach((item) => {
        this.entitysProperties.forEach((e) => {
          if (item === e.entityId + "") {
            let entity = {
              entityName: e.entityName,
              entityIdentify: e.entityIdentify,
              entityId: e.entityId,
              pkgName: e.pkgName,
            };
            this.checkEntitys.push(entity);
          }
        });
      });
    },

    addRule() {
      constant.clearTag(this);
      this.$router.push({ path: "/drools-ruleConfig/rule/add-or-update" });
    },
    editRule(id) {
      constant.clearTag(this);
      this.$router.push({
        path: "/drools-ruleConfig/rule/add-or-update/" + id + "/ae",
      });
    },
    // 启用禁用
    edit(row) {
      let data = row;
      if (row.isEffect === "0") {
        data.isEffect = "1";
      } else {
        data.isEffect = "0";
      }
      updateData(JSON.stringify(data)).then((res) => {
        this.getDataList();
      });
    },
    // 重置查询条件
    resetData() {
      this.dataForm.ruleName = "";
    },
    // 每页数
    sizeChangeHandle(val) {
      this.page.pageSize = val;
      this.page.pageIndex = 1;
      this.getDataList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.page.pageIndex = val;
      this.getDataList();
    },

    // 获取数据列表
    getDataList() {
      if (!this.dataForm.groupIdentify) {
        this.dataList = [];
        return;
      }
      let params = {
        pageNumber: this.page.pageIndex,
        pageSize: this.page.pageSize,
        groupIdentify: this.dataForm.groupIdentify,
      };
      pageData(params).then((res) => {
        this.dataList = res.data.data.list;
        this.page.totalPage = res.data.data.totalCount;
      });
    },
    // initDivisor() {
    //     let params = {
    //         is_effect: '1'
    //     }
    //     listConditionDivisorData(params).then(res => {
    //         this.conditionDivisorList = res.data.data
    //     })
    //     listActionDivisorData(params).then(res => {
    //         this.actionDivisorList = res.data.data
    //     })
    // },

    init(id, type) {
      this.visible = true;
      this.isDisabled = false;
      this.entitysProperties = [];
      this.checkEntity = [];
      // this.initDivisor()

      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();

        if (id && id != "undefined") {
          this.dataForm.id = id;
          this.isDisabled = true;
          let params = {
            id: this.dataForm.id + "",
            groupType: type,
          };
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          getData(params)
            .then((res) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
              if (res.data.data && res.data.resultCode === 0) {
                this.dataForm = res.data.data.groupInfo;
                res.data.data.relList.forEach((item) => {
                  this.checkEntity.push(item.entityId + "");
                });
                this.getEntityProperties();
                if (this.dataForm.groupType === "2") {
                  // this.initDecision();
                } else {
                  this.getDataList();
                }
              }
            })
            .catch((err) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
            });
        } else {
          this.dataForm.groupType = "2";
          this.getEntityProperties();
        }
      });
    },

    // 获取实体类的属性
    getEntityProperties() {
      entityList({}).then((res) => {
        if (res.data.data) {
          this.entitysProperties = [];
          res.data.data.forEach((item) => {
            item["label"] = item.entityIdentify + " -- " + item.entityName;
            this.entitysProperties.push(item);
          });
          this.initEntity();
        }
      });
    },
    // 普通表
    // 表单提交
    dataFormSubmit2() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.itemDataForm.itemData = [];
          this.checkEntity.forEach((item) => {
            this.entitysProperties.forEach((e) => {
              if (item === e.entityId + "") {
                let entity = {
                  entityName: e.entityName,
                  entityIdentify: e.entityIdentify,
                  entityId: e.entityId,
                };
                this.itemDataForm.itemData.push(entity);
              }
            });
          });
          if (this.itemDataForm.itemData.length <= 0) {
            this.$message.error("请先关联模型");
            return;
          }
          let params = {
            groupInfo: JSON.stringify(this.dataForm),
            relList: JSON.stringify(this.itemDataForm.itemData),
            versionType: this.versionType,
          };
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          saveData(params)
            .then((res) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
              if (res.data && res.data.resultCode === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.dataForm = {
                      id: null,
                      groupName: "",
                      groupDesc: "",
                      groupIdentify: "",
                      remark: "",
                      isEffect: "1",
                    };
                    this.itemDataForm.itemData = [];
                    this.entitysProperties = [];
                    this.checkEntity = [];
                    // this.$emit('refreshDataList')
                    this.toList();
                  },
                });
              } else {
                this.$message.error(res.data.resultMsg);
              }
            })
            .catch((err) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
            });
        }
      });
    },
    // 决策表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.itemDataForm.itemData = [];
          this.checkEntity.forEach((item) => {
            this.entitysProperties.forEach((e) => {
              if (item === e.entityId + "") {
                let entity = {
                  entityName: e.entityName,
                  entityIdentify: e.entityIdentify,
                  entityId: e.entityId,
                };
                this.itemDataForm.itemData.push(entity);
              }
            });
          });
          if (this.itemDataForm.itemData.length <= 0) {
            this.$message.error("请先关联模型");
            return;
          }
          let values = [];
          let tableDatas = this.$refs.desionOrUpdate.tableDatas;
          let conditionList = this.$refs.desionOrUpdate.conditionList;

          //获取记录
          let recodes = this.$refs.desionOrUpdate.recodes;
          recodes["isEntityEdit"] = this.isEntityEdit;

          if (tableDatas.length > 0) {
            for (var i = 0; i < tableDatas.length; i++) {
              let data = tableDatas[i];
              if (data) {
                conditionList.forEach((item) => {
                  if (data[item.decisionCode]) {
                    data[item.decisionCode]["rowIndex"] = i;
                    values.push(data[item.decisionCode]);

                    if (item.decisionCode === "RCODE" && data[item.decisionCode]["editType"]) {
                      if (data[item.decisionCode]["editType"] === constant.ADD) {
                        recodes.addRows.push(i);
                      }
                      if (data[item.decisionCode]["editType"] === constant.EDIT) {
                        recodes.editRows.push(i);
                      }
                      if (data[item.decisionCode]["editType"] === constant.DEL) {
                        recodes.delRows.push(i);
                      }
                    }
                  }
                });
              }
            }
          }
          this.dataForm.channelCode = this.$store.state.channel.channelCode;
          let params = {
            groupInfo: JSON.stringify(this.dataForm),
            relList: JSON.stringify(this.itemDataForm.itemData),
            heads: JSON.stringify(this.$refs.desionOrUpdate.conditionList),
            values: JSON.stringify(values),
            delList: JSON.stringify(this.$refs.desionOrUpdate.delList),
            delHeadList: JSON.stringify(this.$refs.desionOrUpdate.delHeadList),
            taskInfo: JSON.stringify(this.$store.state.checktaskInfo),
            versionType: this.versionType,
            recodes: JSON.stringify(recodes)
          };
          this.$store.dispatch("loading/CHANGE_LOADING", true);
          saveRuleGroup(params)
            .then((res) => {
              this.$store.dispatch("loading/CHANGE_LOADING", false);
              if (res.data && res.data.resultCode === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.dataForm = {
                      id: null,
                      groupName: "",
                      groupDesc: "",
                      groupIdentify: "",
                      remark: "",
                      isEffect: "1",
                    };
                    this.itemDataForm.itemData = [];
                    this.entitysProperties = [];
                    this.checkEntity = [];
                    // this.$emit('refreshDataList')
                    this.toList();
                  },
                });
              } else {
                this.$message.error(res.data.resultMsg);
              }
            })
        }
      });
    },
  },
  filters: {
    isEffectFilter: function (value) {
      let label = "";
      if (value === "0") {
        label = "失效";
      } else if (value === "1") {
        label = "有效";
      }
      return label;
    },
  },
};
</script>

<style lang="scss">
.el-table__row .el-form-item__content {
  margin-left: 0 !important;
}

.el-table__row .el-form-item {
  margin-bottom: 0 !important;
}
</style>
<style lang="less" scoped>
body .el-table th.gutter {
  display: table-cell !important;
}

.current-task {
  margin: 20px;

  span {
    font-size: 16px;
    font-weight: 900;
    margin-right: 10px;
  }

  .el-dropdown span {
    font-size: 14px;
    color: #ff0000;
  }
}
</style>
